package com.lori.netshop.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lori.netshop.mapper.TbContentMapper;
import com.lori.netshop.pojo.TbContent;
import com.lori.netshop.pojo.TbContentExample;
import com.lori.netshop.pojo.TbContentExample.Criteria;
import com.lori.netshop.service.ContentCatService;
import com.lori.netshop.service.ContentService;
import com.lori.netshop.util.HttpClientUtil;
import com.lori.netshop.util.NetshopResult;
@Service
public class ContentServiceimp implements ContentService {
	@Autowired
	private TbContentMapper tbContentMapper;
	//获得资源文件的值
	@Value("${REDIS_CONTENT_SYNC_URL}")
	private String REDIS_CONTENT_SYNC_URL;
	@Value("${REDIS_BASE_URL}")
	private String REDIS_BASE_URL;
	/**
	 * 功能：全部或根据内容分类id获得分页数据
	 */
	@Override
	public Map queryContent(Integer page,Integer rows,long categoryId) {
		//添加条件
		TbContentExample example = new TbContentExample();
		Criteria criteria = example.createCriteria();
		if(categoryId != 0 ){
			criteria.andCategoryIdEqualTo(categoryId);
		}
		//分页
		PageHelper.startPage(page, rows);
		//获得数据
		List<TbContent> contentlist = tbContentMapper.selectByExample(example);
		//获得分页信息
		PageInfo<TbContent> pageinfo = new PageInfo<TbContent>(contentlist);
		long total = pageinfo.getTotal();
		//创建集合
		Map map = new HashMap();
		map.put("total", total);
		map.put("rows", contentlist);
		return map;
	}
	/**
	 * 功能：保存一个tb_content的pojo信息
	 * 
	 */
	@Override
	public NetshopResult save(TbContent tbcontent) {
		//补全信息
		tbcontent.setCreated(new Date());
		tbcontent.setUpdated(new Date());
		tbContentMapper.insert(tbcontent);
		//删除对应categoryId对应的缓存
		try {
			String doGet = HttpClientUtil.doGet(REDIS_BASE_URL+REDIS_CONTENT_SYNC_URL+tbcontent.getCategoryId());
		} catch (Exception e) {
			//通知管理员
		}
		return NetshopResult.ok();
	}
	/**
	 * 功能：根据id修改pojo
	 * 
	 */
	@Override
	public NetshopResult edit(TbContent tbcontent) {
		tbContentMapper.updateByPrimaryKeySelective(tbcontent);
		return NetshopResult.ok();
	}
	/**
	 * 功能：根据ids批量删除数据
	 * 
	 */
	@Override
	public NetshopResult delete(long[] ids) {
		for (int i = 0; i < ids.length; i++) {
			tbContentMapper.deleteByPrimaryKey(ids[i]);
		}
		return NetshopResult.ok();
	}

}
